package com.smdt.tools.log.conf;

import com.smdt.tools.log.handler.LogHandler;
import com.smdt.tools.log.handler.NothingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 * 自动配置类
 * @author guass
 */
@ComponentScan
@Configuration
@EnableConfigurationProperties(LogProperties.class)
public class AopLogAutoConfiguration {

    @Resource
    private LogProperties aopLogProperties;

    private static final Logger log = LoggerFactory.getLogger(AopLogAutoConfiguration.class);



    /**
     * 默认配置一个空的收集器
     *
     * @return By default, an empty collector is configured
     */
    @Bean
    @ConditionalOnMissingBean(value = LogHandler.class)
    public LogHandler nothingCollector() {
        return new NothingHandler();
    }


    /**
     * 默认配置异步收集器线程池
     *
     * @return The asynchronous collector thread pool is configured by default
     */
    @Bean(name = "collectorAsyncExecutor")
    @ConditionalOnMissingBean(name = "collectorAsyncExecutor")
    public Executor collectorAsyncExecutor() {
        log.info("smdt log {}",aopLogProperties.getCorePoolSize());
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(aopLogProperties.getCorePoolSize());
        executor.setMaxPoolSize(aopLogProperties.getMaxPoolSize());
        executor.setQueueCapacity(aopLogProperties.getQueueCapacity());
        executor.setThreadNamePrefix(aopLogProperties.getThreadNamePrefix());
        executor.setRejectedExecutionHandler((r, exec) -> log.error("collectorAsyncExecutor thread queue is full,activeCount:{},Subsequent collection tasks will be rejected,please check your LogCollector or config your Executor", exec.getActiveCount()));
        executor.initialize();
        return executor;
    }
}
